package com.keqing.tomato.fragment;


import static android.widget.Toast.LENGTH_SHORT;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.keqing.tomato.LandscapeActivity;
import com.keqing.tomato.R;
import com.keqing.tomato.service.TimerService;
import com.keqing.tomato.state.BeginFocusState;
import com.keqing.tomato.state.State;
import com.keqing.tomato.util.ButtonUtil;
import com.keqing.tomato.util.PreferenceUtil;


public class FragmentTomatoTime extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    public PreferenceUtil.MySetting mySetting;
    public ToggleButton timeModeBtn;
    public Button beginFocusBtn;
    public Button focusingBtn;
    public Button beginRestBtn;
    public Button restingBtn;
    public TextView tvEndTime;
    public Activity activity;
    public TextView tvTime;
    public BroadcastReceiver broadcastReceiver;
    public TimerService timerService;

    private final ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("com/keqing/tomato", "ServiceConnection - onServiceConnected()");
            TimerService.TimerServiceBinder binder = (TimerService.TimerServiceBinder) service;
            timerService = binder.getTimerService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("com/keqing/tomato", "ServiceConnection - onServiceDisconnected()");

        }
    };

    private State state;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.e("com/keqing/tomato", "FragmentTomatoTime - onCreateView");
        return inflater.inflate(R.layout.fragment_tomato_time, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.e("com/keqing/tomato", "FragmentTomatoTime - onViewCreated");
        activity = getActivity();
        mySetting = PreferenceUtil.getMySetting(activity);

        beginFocusBtn = view.findViewById(R.id.begin_focus_btn);
        focusingBtn = view.findViewById(R.id.focusing_btn);
        beginRestBtn = view.findViewById(R.id.begin_rest_btn);
        restingBtn = view.findViewById(R.id.resting_btn);

        TextView resetBtn = view.findViewById(R.id.btn_reset);
        tvTime = view.findViewById(R.id.tv_time);

        TextView landscapeBtn = view.findViewById(R.id.btn_landscape);
        timeModeBtn = view.findViewById(R.id.btn_time_mode);
        tvEndTime = view.findViewById(R.id.tv_end_time);

        beginFocusBtn.setOnClickListener(this);
        focusingBtn.setOnClickListener(this);
        beginRestBtn.setOnClickListener(this);
        restingBtn.setOnClickListener(this);
        resetBtn.setOnClickListener(this);
        landscapeBtn.setOnClickListener(this);
        timeModeBtn.setOnCheckedChangeListener(this);

        //绑定service
        Intent intent = new Intent(activity.getApplicationContext(), TimerService.class);
        activity.bindService(intent, conn, Context.BIND_AUTO_CREATE);

        //注册广播
        registerBroadcastReceivers();

        this.changeState(new BeginFocusState());
        state.initPage();
    }

    public void changeState(State state){
        this.state = state;
        this.state.setContext(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            Log.e("com/keqing/tomato", "FragmentTomatoTime - onHiddenChanged() ：" + hidden);
            state.initPage();
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if (ButtonUtil.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.btn_landscape:
                clickLandscape();
                break;
            case R.id.btn_reset:
                state.clickReset();
                break;
            case R.id.begin_focus_btn:
                state.clickBeginFocus();
                break;
            case R.id.focusing_btn:
                Toast.makeText(activity, "专注中，不要玩手机了", LENGTH_SHORT).show();
                break;
            case R.id.begin_rest_btn:
                state.clickBeginRest();
                break;
            case R.id.resting_btn:
                Toast.makeText(activity, "休息中，远眺一下吧", LENGTH_SHORT).show();
                break;
        }
    }

    public void clickLandscape() {
        Intent intent = new Intent(activity, LandscapeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("time", tvTime.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent, 100);
    }


    private void registerBroadcastReceivers() {
        this.broadcastReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                Bundle bundle = intent.getExtras();
                String minSec = intent.getExtras().getString("minSec");
                tvTime.setText(minSec);
                if (bundle.getInt("what") == TimerService.time_finished) {
                    state.doTimerFinish();
                }
            }
        };
        activity.registerReceiver(this.broadcastReceiver, new IntentFilter("timer"));
    }


    //正计时、倒计时按钮事件
    //选中：正计时
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.e("tomato", "is : " + isChecked);
        state.clickTimeMode();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.e("com/keqing/tomato", "FragmentTomatoTime - onActivityResult()");
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("com/keqing/tomato", "FragmentTomatoTime - onDestroy");
        activity.unbindService(conn);
        activity.unregisterReceiver(this.broadcastReceiver);
        timerFinishHandler.removeCallbacksAndMessages(null);
    }

    public final Handler timerFinishHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            state.initPage();
            Intent intent = new Intent("timer");
            intent.putExtra("minSec", tvTime.getText().toString());
            activity.sendBroadcast(intent);
        }
    };

}